<template>
    <a-spin :spinning="viewLoading" :style="spinStyle">
        <a-row>
            <a-space :size="20">
                <a-space>
                    <span>规则名称</span>
                    <a-input v-model:value="rule_name" placeholder="请输入"></a-input>
                </a-space>
                <a-space>
                    <span>规则备注</span>
                    <a-input v-model:value="description" placeholder="请输入"></a-input>
                </a-space>
                <a-space>
                    <span>文章内容分类</span>
                    <a-input v-model:value="content_type" placeholder="请输入"></a-input>
                </a-space>
                <slot name="back"></slot>
                <a-button :loading="saveBtnLoading" type="primary" @click="saveRule"
                    >{{ saveRuleBtnText }}
                    <template #icon>
                        <SaveOutlined />
                    </template>
                </a-button>
                <a-button type="primary" @click="openModal">内容设置 </a-button>
            </a-space>
            <a-divider>筛选条件</a-divider>
            <a-space :size="20">
                <a-space>
                    <span>生成服务器</span>
                    <a-select
                        :options="esHostOptionsCopy"
                        v-model:value="generate_host"
                        placeholder="请选择"
                        style="width: 140px"
                        show-search
                        :filter-option="filterOption"
                    ></a-select>
                </a-space>
                <a-space>
                    <template v-if="generate_host.includes('160.181.180.2')">
                        <span>目标索引</span>
                        <a-select
                            placeholder="文章存放索引"
                            :options="originEsIndexOptions"
                            v-model:value="generate_index"
                            style="width: 200px"
                            show-search
                            :filter-option="filterOption"
                        ></a-select>
                    </template>
                    <template v-else>
                        <span>生成索引</span>
                        <a-input placeholder="文章存放索引" v-model:value="generate_index" style="width: 150px"></a-input>
                    </template>
                </a-space>
                <a-space>
                    <span>网站组</span>
                    <a-select
                        :options="websiteGroupOptions"
                        v-model:value="website_group_id"
                        placeholder="请选择"
                        style="width: 120px"
                        show-search
                        :filter-option="filterOption"
                    ></a-select>
                </a-space>
                <a-space>
                    <span>行业类型</span>
                    <a-select
                        :options="websiteTypeOptions"
                        v-model:value="trade_type_id"
                        placeholder="请选择"
                        style="width: 110px"
                        show-search
                        :filter-option="filterOption"
                    ></a-select>
                </a-space>
                <a-space>
                    <span>创建者</span>
                    <a-select
                        :options="userOptions"
                        v-model:value="create_id"
                        placeholder="请选择"
                        style="width: 100px"
                        show-search
                        :filter-option="filterOption"
                    ></a-select>
                </a-space>
            </a-space>
            <a-divider>关键词</a-divider>
            <a-space>
                目标关键词
                <a-radio-group v-model:value="is_target" :options="targetKeywordOptions" />
                <a-textarea v-model:value="keywords" :placeholder="keywordsPlaceholder" style="width: 260px; min-height: 80px" />
            </a-space>
            <a-divider>敏感词替换</a-divider>
            <a-space>
                <a-switch
                    checked-children="使用索引"
                    un-checked-children="输入词"
                    v-model:checked="replace_data.sensitive_words.is_index"
                />
                <EsHostAndIndexSelectAndField
                    v-model:data="replace_data.sensitive_words"
                    v-if="replace_data.sensitive_words.is_index"
                />
                <a-textarea
                    v-model:value="replace_data.sensitive_words.keywords"
                    placeholder="输入词 换行隔开"
                    style="width: 240px"
                    v-else
                />
            </a-space>
            <a-divider>杂质替换</a-divider>
            <a-space>
                <a-switch
                    checked-children="使用索引"
                    un-checked-children="输入词"
                    v-model:checked="replace_data.impurity.is_index"
                />
                <EsHostAndIndexSelectAndField v-model:data="replace_data.impurity" v-if="replace_data.impurity.is_index" />
                <a-textarea
                    v-model:value="replace_data.impurity.keywords"
                    placeholder="输入词 换行隔开"
                    style="width: 240px"
                    v-else
                />
            </a-space>
            <a-divider>标题设置</a-divider>
            <a-row>
                <EsHostAndIndexSelectAndField v-model:data="title_data" />
                <a-space style="margin-left: 10px">
                    <a-switch checked-children="使用连接符" un-checked-children="不使用" v-model:checked="title_data.isJoin" />
                    <a-space v-if="title_data.isJoin">
                        连接符<a-input v-model:value="title_data.joinChar" style="width: 60px"></a-input>
                        连接位置
                        <a-select
                            :options="positionOptions2"
                            style="width: 80px"
                            v-model:value="title_data.joinPosition"
                        ></a-select>
                    </a-space>
                    <a-space v-else>
                        前缀<a-input v-model:value="title_data.prefix" style="width: 120px"></a-input> 后缀<a-input
                            v-model:value="title_data.suffix"
                            style="width: 120px"
                        ></a-input>
                    </a-space>
                </a-space>
            </a-row>
            <a-divider>图片设置</a-divider>
            <a-row>
                <EsHostAndIndexSelectAndField v-model:data="img_data" />
            </a-row>
            <a-divider>随机内链设置</a-divider>
            <a-row>
                <a-space>
                    内链<a-textarea
                        v-model:value="random_link_data.links"
                        placeholder="换行隔开"
                        style="width: 500px; height: 80px"
                    />
                    位置<a-radio-group v-model:value="random_link_data.position" :options="positionOptions"></a-radio-group>
                </a-space>
            </a-row>
            <a-divider>首段设置</a-divider>
            <a-row>
                <EsHostAndIndexSelectAndField v-model:data="first_section_data" />
            </a-row>
            <a-divider>尾段设置</a-divider>
            <a-row>
                <EsHostAndIndexSelectAndField v-model:data="footer_section_data" />
            </a-row>
            <a-divider>正文段落设置</a-divider>
            <a-row :gutter="[0, 10]">
                <a-col v-for="(main_body_item, index) in main_body_section_data" :key="main_body_item.id">
                    <EsHostAndIndexSelectAndField v-model:data="main_body_item.value" />
                    <a-button type="link" @click="removeMainBodyItem(main_body_section_data, index)" danger> 删除 </a-button>
                </a-col>
                <a-col>
                    <a-button style="width: 100%" type="dashed" block @click="addMainBodyItem(main_body_section_data)">
                        <PlusOutlined />
                        添加配置项
                    </a-button>
                </a-col>
            </a-row>
            <a-divider>问答设置</a-divider>
            <a-row>
                <a-space>
                    <EsHostAndIndexSelectAndField v-model:data="reply_data" />
                </a-space>
            </a-row>
            <a-divider>经历设置</a-divider>
            <a-row>
                <a-space>
                    <EsHostAndIndexSelectAndField v-model:data="undergo_data" />
                </a-space>
            </a-row>
            <a-divider>表格设置</a-divider>
            <a-row>
                <a-space>
                    <EsHostAndIndexSelectAndField v-model:data="table_data" />
                </a-space>
            </a-row>
            <a-divider>句子设置</a-divider>
            <a-row>
                <a-space>
                    <EsHostAndIndexSelectAndField v-model:data="sentence_data" />
                </a-space>
            </a-row>
            <a-modal v-model:open="isShowModal" title="添加内容项" @ok="modalOk" width="92%" wrap-class-name="full-modal">
                <a-typography-paragraph>
                    每添加一个内容项,代表生成的文章会使用一次这个内容,且按 <a-typography-text mark>顺序排列</a-typography-text>。
                </a-typography-paragraph>
                <a-typography-paragraph>
                    自定义样式中的文字会被替换。<a-typography-text code>;</a-typography-text>。</a-typography-paragraph
                >
                <AddComposeRuleContentItem v-model:data="content_data" />
            </a-modal>
        </a-row>
    </a-spin>
</template>

<script lang="ts" setup>
    import { useCommonAsyncOptions, useCommonStaticOptions } from "@/hooks/useEsArticleCommon";
    import AddComposeRuleContentItem from "@/tsx/composeRule/AddComposeRuleContentItem";
    import EsHostAndIndexSelectAndField from "@/tsx/composeRule/EsHostAndIndexSelectAndField";
    import { randomId } from "@/utils/common";
    import { SaveOutlined, PlusOutlined } from "@ant-design/icons-vue";
    import { useVModel, computedAsync } from "@vueuse/core";
    import { useSpinLoadingState } from "@/hooks/useCommon";
    import { message } from "ant-design-vue";
    import { getEsIndexsApi } from "@/api/esArticle";
    const saveBtnLoading = ref(false);
    const { userOptions, websiteGroupOptions, websiteTypeOptions } = useCommonAsyncOptions();
    const { filterOption, positionOptions, esHostOptions, targetKeywordOptions } = useCommonStaticOptions();
    const esHostOptionsCopy = JSON.parse(JSON.stringify(esHostOptions));
    esHostOptionsCopy.push({
        label: "160.181.180.2",
        value: "http://160.181.180.2:9000"
    });
    const positionOptions2 = [
        {
            label: "左边",
            value: "left"
        },
        {
            label: "右边",
            value: "right"
        }
    ];
    type Props = {
        rule: PostComposeRuleParmas;
        saveRuleBtnText: string;
    };
    type Emits = {
        (event: "update:rule"): void;
        (event: "save:rule"): void;
    };
    const emits = defineEmits<Emits>();
    const props = defineProps<Props>();
    const rule = useVModel(props, "rule", emits);
    const {
        content_data,
        replace_data,
        img_data,
        sentence_data,
        table_data,
        undergo_data,
        reply_data,
        main_body_section_data,
        footer_section_data,
        first_section_data,
        random_link_data,
        rule_name,
        description,
        create_id,
        keywords,
        website_group_id,
        generate_host,
        generate_index,
        trade_type_id,
        is_target,
        title_data,
        content_type
    } = toRefs(rule.value);
    const { spinStyle, viewLoading } = useSpinLoadingState();
    // 关键词 输入提示
    const keywordsPlaceholder = computed(() => (rule.value.is_target ? "输入目标关键词网站列表" : "输入关键词列表"));
    // 是否显示对话框
    const isShowModal = ref(false);
    // 添加配置(例如正文段落 需要多个设置)
    const addMainBodyItem = (values: Array<MultipleConfigItem>) => {
        values.push({
            id: randomId(),
            value: { index: "", host: "http://192.168.1.92:9200", content_field: "", title_field: "" }
        });
    };
    // 删除配置
    const removeMainBodyItem = (values: Array<MultipleConfigItem>, index: number) => {
        values.splice(index, 1);
    };
    // 是否收集数据
    const isCollect = ref(false);
    provide("isCollect", isCollect);
    // 打开对话框
    const openModal = () => {
        isShowModal.value = true;
        isCollect.value = false;
    };
    // 对话框确定
    const modalOk = () => {
        // 更新isCollect的值 触发子组件收集数据
        isCollect.value = true;
        isShowModal.value = false;
    };
    // 保存规则
    const saveRule = () => {
        // 可以为空的字段
        const allowNullFields = ["impurityReplace", "sensitiveWordsReplace"];
        let key: keyof PostComposeRuleParmas;
        // 索引服务器 内容字段 为多个的 一些字段名
        const valueIsArrFields = ["main_body_section_data"];
        for (key in rule.value) {
            if (typeof rule.value[key] === "object") {
                // @ts-ignore
                for (const key2 in rule.value[key]) {
                    // @ts-ignore
                    if (!rule.value[key][key2]) {
                        if (key2 === "index") {
                            return message.error("请选择索引!");
                        } else if (key2 === "title_field") {
                            return message.error("请选择标题字段!");
                        } else if (key2 === "content_field") {
                            return message.error("请选择内容字段!");
                        }
                    }
                    if (valueIsArrFields.includes(key) && Array.isArray(rule.value[key])) {
                        // @ts-ignore
                        for (const item of rule.value[key]) {
                            if (!item["value"]["index"]) {
                                return message.error("请选择索引!");
                            } else if (!item["value"]["title_field"]) {
                                return message.error("请选择标题字段!");
                            } else if (!item["value"]["content_field"]) {
                                return message.error("请选择内容字段!");
                            }
                        }
                    }
                }
            }
            if (!allowNullFields.includes(key) && !rule.value[key]) {
                if (key === "keywords") {
                    message.error("请填写关键词,或输入域名!");
                    return;
                }
                if (key === "rule_name") {
                    message.error("请输入规则名!");
                    return;
                }
                if (key === "description") {
                    message.error("请输入备注!");
                    return;
                }
                if (key === "generate_index") {
                    message.error("文章生成索引!");
                    return;
                }
                if (key === "create_id") {
                    message.error("请选择创建者!");
                    return;
                }
            }
        }
        if (content_data.value.length < 2) {
            message.error("请完成内容设置!");
            return;
        }
        emits("save:rule");
    };
    const originEsIndexOptions = computedAsync(async () => {
        const res = await getEsIndexsApi(generate_host.value);
        if (res.data.code === 200) {
            // 返回的Promise
            return res.data.data.map((index: string) => ({ label: index, value: index }));
        } else {
            return [];
        }
    });
    onMounted(() => {
        setTimeout(() => {
            viewLoading.value = false;
        }, 1500);
    });
</script>

<style scoped lang="scss"></style>
